<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>岚小字识字系统 - 字根数据管理</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .app-container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: rgba(255,255,255,0.95);
            padding: 20px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 8px;
        }

        .stat-label {
            color: #666;
            font-size: 14px;
        }

        .main-table {
            background: rgba(255,255,255,0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
        }

        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .search-bar {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .search-input {
            padding: 10px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 25px;
            outline: none;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .search-input:focus {
            border-color: #667eea;
        }

        .action-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s;
            margin-left: 8px;
        }

        .btn-primary { background: #667eea; color: white; }
        .btn-success { background: #48bb78; color: white; }
        .btn-secondary { background: #e2e8f0; color: #4a5568; }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }

        .radical-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }

        .radical-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 18px 12px;
            text-align: center;
            font-weight: 600;
            font-size: 14px;
        }

        .radical-table td {
            padding: 15px 12px;
            text-align: center;
            border-bottom: 1px solid #f0f0f0;
            vertical-align: middle;
        }

        .radical-table tr:hover {
            background: #f8f9ff;
        }

        .radical-char {
            font-size: 2.5rem;
            font-weight: bold;
            color: #667eea;
            text-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        .radical-number {
            font-weight: bold;
            color: #667eea;
            font-size: 16px;
        }

        .pinyin-text {
            font-size: 16px;
            color: #4a5568;
            font-weight: 500;
        }

        .edit-btn {
            padding: 8px 16px;
            border: 1px solid #667eea;
            background: white;
            color: #667eea;
            border-radius: 20px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.3s;
        }

        .edit-btn:hover {
            background: #667eea;
            color: white;
            transform: scale(1.05);
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 30px;
            gap: 10px;
            flex-wrap: wrap;
        }

        .page-btn {
            padding: 8px 12px;
            border: 1px solid #e2e8f0;
            background: white;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .page-btn:hover, .page-btn.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        /* 弹窗样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.6);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            backdrop-filter: blur(5px);
        }

        .modal-overlay.show {
            display: flex;
        }

        .editor-modal {
            background: white;
            border-radius: 20px;
            width: 90%;
            max-width: 1200px;
            max-height: 90vh;
            overflow: hidden;
            box-shadow: 0 25px 100px rgba(0,0,0,0.3);
            animation: modalSlideIn 0.3s ease;
        }

        @keyframes modalSlideIn {
            from { opacity: 0; transform: scale(0.9) translateY(20px); }
            to { opacity: 1; transform: scale(1) translateY(0); }
        }

        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-size: 20px;
            font-weight: 600;
        }

        .close-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            width: 35px;
            height: 35px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
            transition: background 0.3s;
        }

        .close-btn:hover {
            background: rgba(255,255,255,0.3);
        }

        .modal-content {
            padding: 30px;
            height: 600px;
            overflow-y: auto;
        }

        .ai-fill-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .ai-fill-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }

        .ai-fill-btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }

        .radical-preview {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            margin-bottom: 20px;
        }

        .radical-preview .char {
            font-size: 4rem;
            font-weight: bold;
            text-shadow: 0 2px 8px rgba(0,0,0,0.3);
        }

        .radical-preview .info {
            text-align: center;
        }

        .editor-sections {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #2d3748;
            font-size: 13px;
        }

        .form-input, .form-textarea {
            width: 100%;
            padding: 10px 12px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            outline: none;
            font-size: 14px;
            transition: border-color 0.3s;
            font-family: inherit;
        }

        .form-textarea {
            height: 100px;
            resize: vertical;
        }

        .form-input:focus, .form-textarea:focus {
            border-color: #667eea;
        }

        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid #e2e8f0;
        }

        .save-btn {
            width: 100%;
            padding: 12px;
            background: #48bb78;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }

        .save-btn:hover {
            background: #38a169;
        }

        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .hidden { display: none; }

        @media (max-width: 768px) {
            .editor-sections {
                grid-template-columns: 1fr;
            }
            .form-grid {
                grid-template-columns: 1fr;
            }
            .table-header {
                flex-direction: column;
                align-items: stretch;
            }
            .search-bar {
                justify-content: center;
            }
        }

        .status-badges {
            display: flex;
            flex-direction: column;
            gap: 5px;
            align-items: center;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            white-space: nowrap;
        }

        .status-badge.completed {
            background: #e6fffa;
            color: #038a67;
            border: 1px solid #81e6d9;
        }

        .status-badge.pending {
            background: #fef5e7;
            color: #b7791f;
            border: 1px solid #fbd38d;
        }

        .status-badge.visible {
            background: #e6f7ff;
            color: #0c4a6e;
            border: 1px solid #7dd3fc;
        }

        .status-badge.hidden {
            background: #fce7f3;
            color: #be185d;
            border: 1px solid #f9a8d4;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
            justify-content: center;
            flex-wrap: wrap;
        }

        .toggle-btn {
            padding: 6px 12px;
            border: 1px solid #cbd5e0;
            background: white;
            border-radius: 15px;
            cursor: pointer;
            font-size: 11px;
            font-weight: 600;
            transition: all 0.3s;
        }

        .toggle-btn.hide {
            color: #dc2626;
            border-color: #fca5a5;
        }

        .toggle-btn.hide:hover {
            background: #fee2e2;
            border-color: #dc2626;
        }

        .toggle-btn.show {
            color: #059669;
            border-color: #6ee7b7;
        }

        .toggle-btn.show:hover {
            background: #d1fae5;
            border-color: #059669;
        }

        .hidden-row {
            opacity: 0.5;
            background: #f9f9f9;
        }

        .hidden-row:hover {
            background: #f0f0f0 !important;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- 头部 -->
        <div class="header">
            <h1>📊 字根数据管理</h1>
            <p>岚小字识字系统 - 字根基础数据库</p>
        </div>

        <!-- 统计卡片 -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number" id="total-count">12</div>
                <div class="stat-label">总字根数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="completed-count">6</div>
                <div class="stat-label">已完善</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="course-count">10</div>
                <div class="stat-label">课程中</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="hidden-count">2</div>
                <div class="stat-label">已隐藏</div>
            </div>
        </div>

        <!-- 主表格 -->
        <div class="main-table">
            <div class="table-header">
                <h2>📋 字根数据表</h2>
                <div class="search-bar">
                    <input 
                        type="text" 
                        placeholder="搜索字根、拼音..." 
                        class="search-input"
                        id="search-input">
                    <button class="action-btn btn-success" onclick="addNewRadical()">
                        ➕ 新增字根
                    </button>
                    <button class="action-btn btn-primary" onclick="importData()">
                        📥 导入数据
                    </button>
                    <button class="action-btn btn-secondary" onclick="exportData()">
                        📤 导出数据
                    </button>
                </div>
            </div>

            <table class="radical-table">
                <thead>
                    <tr>
                        <th style="width: 80px;">编号</th>
                        <th style="width: 120px;">字根</th>
                        <th style="width: 120px;">读音</th>
                        <th style="width: 80px;">状态</th>
                        <th style="width: 140px;">操作</th>
                    </tr>
                </thead>
                <tbody id="radical-tbody">
                    <!-- 数据将通过JavaScript动态填充 -->
                </tbody>
            </table>

            <!-- 分页 -->
            <div class="pagination" id="pagination">
                <!-- 分页按钮将通过JavaScript动态生成 -->
            </div>
        </div>

        <!-- 编辑器弹窗 -->
        <div class="modal-overlay" id="editor-modal">
            <div class="editor-modal">
                <div class="modal-header">
                    <div class="modal-title" id="modal-title">编辑字根</div>
                    <button class="close-btn" onclick="closeEditor()">×</button>
                </div>

                <div class="modal-content">
                    <!-- AI填充按钮 -->
                    <button class="ai-fill-btn" id="ai-fill-btn" onclick="aiAutoFill()">
                        <span id="ai-fill-text">🤖 AI智能填充</span>
                    </button>

                    <!-- 字根预览 -->
                    <div class="radical-preview">
                        <div class="char" id="preview-char">？</div>
                        <div class="info">
                            <div>编号：<span id="preview-number">自动生成</span></div>
                            <div>读音：<span id="preview-pinyin">待填充</span></div>
                            <div>笔画：<span id="preview-strokes">-</span>画</div>
                        </div>
                    </div>

                    <!-- 编辑表单 -->
                    <div class="editor-sections">
                        <!-- 左侧字段 -->
                        <div class="left-section">
                            <h3 class="section-title">📝 基础信息</h3>
                            
                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label">编号</label>
                                    <input type="text" class="form-input" id="edit-number" placeholder="如：001（可自动生成）">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">字根 *</label>
                                    <input type="text" class="form-input" id="edit-character" placeholder="如：土（必填）" oninput="updatePreview()">
                                </div>
                            </div>

                            <div class="form-grid">
                                <div class="form-group">
                                    <label class="form-label">拼音</label>
                                    <input type="text" class="form-input" id="edit-pinyin" placeholder="如：tǔ（AI可填充）" oninput="updatePreview()">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">笔画数</label>
                                    <input type="number" class="form-input" id="edit-strokes" placeholder="如：3（AI可计算）" oninput="updatePreview()">
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="form-label">部首</label>
                                <input type="text" class="form-input" id="edit-radical" placeholder="如：土（AI可识别）">
                            </div>

                            <div class="form-group">
                                <label class="form-label">基本含义</label>
                                <textarea class="form-textarea" id="edit-meaning" placeholder="字根的基本含义和用法（AI可生成）..."></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label">字形特征</label>
                                <textarea class="form-textarea" id="edit-features" placeholder="字根的形状特点、结构特征（AI可分析）..."></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label">记忆技巧</label>
                                <textarea class="form-textarea" id="edit-tips" placeholder="记忆字根的技巧和方法、口诀（AI可创作）..."></textarea>
                            </div>
                        </div>

                        <!-- 右侧字段 -->
                        <div class="right-section">
                            <h3 class="section-title">📖 扩展信息</h3>

                            <div class="form-group">
                                <label class="form-label">演变历程</label>
                                <textarea class="form-textarea" id="edit-evolution" placeholder="从甲骨文到楷书的演变过程（AI可生成）..."></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label">字源故事</label>
                                <textarea class="form-textarea" id="edit-story" placeholder="字根的起源故事和文化内涵（AI可创作）..."></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label">扩展含义</label>
                                <textarea class="form-textarea" id="edit-extended" placeholder="字根在不同语境下的含义（AI可拓展）..."></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label">常用词组</label>
                                <textarea class="form-textarea" id="edit-phrases" placeholder="包含此字根的常用词组（AI可收集）..."></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label">例句练习</label>
                                <textarea class="form-textarea" id="edit-sentences" placeholder="使用该字根的例句（AI可创作）..."></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label">练习题目</label>
                                <textarea class="form-textarea" id="edit-questions" placeholder="相关的练习题目，每行一题（AI可生成）..."></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- 保存按钮 -->
                    <button class="save-btn" onclick="saveRadical()">
                        💾 <span id="save-text">保存修改</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let radicals = [
            { id: 1, number: '001', character: '土', pinyin: 'tǔ', strokes: 3, completed: true, hidden: false, createTime: '2024-01-01' },
            { id: 2, number: '002', character: '一', pinyin: 'yī', strokes: 1, completed: true, hidden: false, createTime: '2024-01-01' },
            { id: 3, number: '003', character: '工', pinyin: 'gōng', strokes: 3, completed: true, hidden: false, createTime: '2024-01-01' },
            { id: 4, number: '004', character: '水', pinyin: 'shuǐ', strokes: 4, completed: false, hidden: false, createTime: '2024-01-01' },
            { id: 5, number: '005', character: '火', pinyin: 'huǒ', strokes: 4, completed: true, hidden: false, createTime: '2024-01-01' },
            { id: 6, number: '006', character: '木', pinyin: 'mù', strokes: 4, completed: false, hidden: false, createTime: '2024-01-01' },
            { id: 7, number: '007', character: '金', pinyin: 'jīn', strokes: 8, completed: false, hidden: true, createTime: '2024-01-01' },
            { id: 8, number: '008', character: '口', pinyin: 'kǒu', strokes: 3, completed: true, hidden: false, createTime: '2024-01-01' },
            { id: 9, number: '009', character: '田', pinyin: 'tián', strokes: 5, completed: false, hidden: false, createTime: '2024-01-01' },
            { id: 10, number: '010', character: '日', pinyin: 'rì', strokes: 4, completed: true, hidden: false, createTime: '2024-01-01' },
            { id: 11, number: '011', character: '月', pinyin: 'yuè', strokes: 4, completed: false, hidden: true, createTime: '2024-01-01' },
            { id: 12, number: '012', character: '山', pinyin: 'shān', strokes: 3, completed: true, hidden: false, createTime: '2024-01-01' }
        ];

        let currentPage = 1;
        let pageSize = 10;
        let searchKeyword = '';
        let isNewRadical = false;
        let currentRadical = null;

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateStatistics();
            renderTable();
            renderPagination();
            
            // 搜索功能
            document.getElementById('search-input').addEventListener('input', function() {
                searchKeyword = this.value.toLowerCase();
                currentPage = 1;
                renderTable();
                renderPagination();
            });
        });

        // 更新统计信息
        function updateStatistics() {
            const total = radicals.length;
            const completed = radicals.filter(r => r.completed).length;
            const hidden = radicals.filter(r => r.hidden).length;
            const courseCount = total - hidden; // 课程中的字根数

            document.getElementById('total-count').textContent = total;
            document.getElementById('completed-count').textContent = completed;
            document.getElementById('course-count').textContent = courseCount;
            document.getElementById('hidden-count').textContent = hidden;
        }

        // 渲染表格
        function renderTable() {
            const tbody = document.getElementById('radical-tbody');
            const filteredRadicals = radicals.filter(radical => 
                radical.character.includes(searchKeyword) ||
                radical.pinyin.toLowerCase().includes(searchKeyword) ||
                radical.number.includes(searchKeyword)
            );

            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            const pageRadicals = filteredRadicals.slice(start, end);

            tbody.innerHTML = pageRadicals.map(radical => `
                <tr class="${radical.hidden ? 'hidden-row' : ''}">
                    <td><div class="radical-number">${radical.number}</div></td>
                    <td><div class="radical-char">${radical.character}</div></td>
                    <td><div class="pinyin-text">${radical.pinyin}</div></td>
                    <td>
                        <div class="status-badges">
                            <span class="status-badge ${radical.completed ? 'completed' : 'pending'}">${radical.completed ? '已完善' : '待完善'}</span>
                            <span class="status-badge ${radical.hidden ? 'hidden' : 'visible'}">${radical.hidden ? '已隐藏' : '课程中'}</span>
                        </div>
                    </td>
                    <td>
                        <div class="action-buttons">
                            <button class="edit-btn" onclick="editRadical(${radical.id})">📝 编辑</button>
                            <button class="toggle-btn ${radical.hidden ? 'show' : 'hide'}" onclick="toggleRadical(${radical.id})">
                                ${radical.hidden ? '👁️ 显示' : '🙈 隐藏'}
                            </button>
                        </div>
                    </td>
                </tr>
            `).join('');
        }

        // 渲染分页
        function renderPagination() {
            const filteredRadicals = radicals.filter(radical => 
                radical.character.includes(searchKeyword) ||
                radical.pinyin.toLowerCase().includes(searchKeyword) ||
                radical.number.includes(searchKeyword)
            );
            
            const totalPages = Math.ceil(filteredRadicals.length / pageSize);
            const pagination = document.getElementById('pagination');

            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }

            let paginationHTML = '';
            
            // 上一页
            if (currentPage > 1) {
                paginationHTML += `<button class="page-btn" onclick="changePage(${currentPage - 1})">上一页</button>`;
            }

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    paginationHTML += `<button class="page-btn active">${i}</button>`;
                } else {
                    paginationHTML += `<button class="page-btn" onclick="changePage(${i})">${i}</button>`;
                }
            }

            // 下一页
            if (currentPage < totalPages) {
                paginationHTML += `<button class="page-btn" onclick="changePage(${currentPage + 1})">下一页</button>`;
            }

            pagination.innerHTML = paginationHTML;
        }

        // 换页
        function changePage(page) {
            currentPage = page;
            renderTable();
            renderPagination();
        }

        // 编辑字根
        function editRadical(id) {
            currentRadical = radicals.find(r => r.id === id);
            isNewRadical = false;
            
            // 填充表单
            document.getElementById('edit-number').value = currentRadical.number || '';
            document.getElementById('edit-character').value = currentRadical.character || '';
            document.getElementById('edit-pinyin').value = currentRadical.pinyin || '';
            document.getElementById('edit-strokes').value = currentRadical.strokes || '';
            document.getElementById('edit-radical').value = currentRadical.radical || '';
            document.getElementById('edit-meaning').value = currentRadical.basicMeaning || '';
            document.getElementById('edit-features').value = currentRadical.shapeFeatures || '';
            document.getElementById('edit-tips').value = currentRadical.memoryTips || '';
            document.getElementById('edit-evolution').value = currentRadical.evolution || '';
            document.getElementById('edit-story').value = currentRadical.originStory || '';
            document.getElementById('edit-extended').value = currentRadical.extendedMeaning || '';
            document.getElementById('edit-phrases').value = currentRadical.commonPhrases || '';
            document.getElementById('edit-sentences').value = currentRadical.exampleSentences || '';
            document.getElementById('edit-questions').value = currentRadical.questions || '';

            // 更新标题和预览
            document.getElementById('modal-title').textContent = `编辑字根 - ${currentRadical.character}`;
            document.getElementById('save-text').textContent = '保存修改';
            updatePreview();
            
            // 显示弹窗
            document.getElementById('editor-modal').classList.add('show');
        }

        // 新增字根
        function addNewRadical() {
            currentRadical = null;
            isNewRadical = true;
            
            // 清空表单
            document.getElementById('edit-number').value = getNextNumber();
            document.getElementById('edit-character').value = '';
            document.getElementById('edit-pinyin').value = '';
            document.getElementById('edit-strokes').value = '';
            document.getElementById('edit-radical').value = '';
            document.getElementById('edit-meaning').value = '';
            document.getElementById('edit-features').value = '';
            document.getElementById('edit-tips').value = '';
            document.getElementById('edit-evolution').value = '';
            document.getElementById('edit-story').value = '';
            document.getElementById('edit-extended').value = '';
            document.getElementById('edit-phrases').value = '';
            document.getElementById('edit-sentences').value = '';
            document.getElementById('edit-questions').value = '';

            // 更新标题
            document.getElementById('modal-title').textContent = '新增字根';
            document.getElementById('save-text').textContent = '添加字根';
            updatePreview();
            
            // 显示弹窗
            document.getElementById('editor-modal').classList.add('show');
        }

        // 获取下一个编号
        function getNextNumber() {
            const maxNum = Math.max(...radicals.map(r => parseInt(r.number)));
            return String(maxNum + 1).padStart(3, '0');
        }

        // 更新预览
        function updatePreview() {
            const char = document.getElementById('edit-character').value || '？';
            const number = document.getElementById('edit-number').value || '自动生成';
            const pinyin = document.getElementById('edit-pinyin').value || '待填充';
            const strokes = document.getElementById('edit-strokes').value || '-';

            document.getElementById('preview-char').textContent = char;
            document.getElementById('preview-number').textContent = number;
            document.getElementById('preview-pinyin').textContent = pinyin;
            document.getElementById('preview-strokes').textContent = strokes;
        }

        // 关闭编辑器
        function closeEditor() {
            document.getElementById('editor-modal').classList.remove('show');
        }

        // 保存字根
        function saveRadical() {
            const character = document.getElementById('edit-character').value;
            if (!character) {
                alert('请填写必填字段：字根');
                return;
            }

            const radicalData = {
                number: document.getElementById('edit-number').value || getNextNumber(),
                character: character,
                pinyin: document.getElementById('edit-pinyin').value,
                strokes: parseInt(document.getElementById('edit-strokes').value) || 0,
                radical: document.getElementById('edit-radical').value,
                basicMeaning: document.getElementById('edit-meaning').value,
                shapeFeatures: document.getElementById('edit-features').value,
                memoryTips: document.getElementById('edit-tips').value,
                evolution: document.getElementById('edit-evolution').value,
                originStory: document.getElementById('edit-story').value,
                extendedMeaning: document.getElementById('edit-extended').value,
                commonPhrases: document.getElementById('edit-phrases').value,
                exampleSentences: document.getElementById('edit-sentences').value,
                questions: document.getElementById('edit-questions').value,
                completed: true
            };

            if (isNewRadical) {
                radicalData.id = Date.now();
                radicalData.createTime = new Date().toISOString().split('T')[0];
                radicalData.hidden = false;
                radicals.push(radicalData);
                alert('字根添加成功！');
            } else {
                const index = radicals.findIndex(r => r.id === currentRadical.id);
                if (index !== -1) {
                    radicals[index] = { ...radicals[index], ...radicalData };
                    alert('字根修改成功！');
                }
            }

            updateStatistics();
            renderTable();
            renderPagination();
            closeEditor();
        }

        // AI自动填充
        function aiAutoFill() {
            const character = document.getElementById('edit-character').value;
            if (!character) {
                alert('请先输入字根字符');
                return;
            }

            const btn = document.getElementById('ai-fill-btn');
            const text = document.getElementById('ai-fill-text');
            
            btn.disabled = true;
            text.innerHTML = '<div class="loading-spinner"></div> AI正在分析字根并生成内容...';

            // 模拟AI填充过程
            setTimeout(() => {
                const sampleData = generateSampleData(character);
                
                // 智能填充：只填充空字段
                if (!document.getElementById('edit-pinyin').value) {
                    document.getElementById('edit-pinyin').value = sampleData.pinyin;
                }
                if (!document.getElementById('edit-strokes').value) {
                    document.getElementById('edit-strokes').value = sampleData.strokes;
                }
                if (!document.getElementById('edit-radical').value) {
                    document.getElementById('edit-radical').value = sampleData.radical;
                }
                if (!document.getElementById('edit-meaning').value) {
                    document.getElementById('edit-meaning').value = sampleData.basicMeaning;
                }
                if (!document.getElementById('edit-features').value) {
                    document.getElementById('edit-features').value = sampleData.shapeFeatures;
                }
                if (!document.getElementById('edit-tips').value) {
                    document.getElementById('edit-tips').value = sampleData.memoryTips;
                }
                if (!document.getElementById('edit-evolution').value) {
                    document.getElementById('edit-evolution').value = sampleData.evolution;
                }
                if (!document.getElementById('edit-story').value) {
                    document.getElementById('edit-story').value = sampleData.originStory;
                }
                if (!document.getElementById('edit-extended').value) {
                    document.getElementById('edit-extended').value = sampleData.extendedMeaning;
                }
                if (!document.getElementById('edit-phrases').value) {
                    document.getElementById('edit-phrases').value = sampleData.commonPhrases;
                }
                if (!document.getElementById('edit-sentences').value) {
                    document.getElementById('edit-sentences').value = sampleData.exampleSentences;
                }
                if (!document.getElementById('edit-questions').value) {
                    document.getElementById('edit-questions').value = sampleData.questions;
                }

                updatePreview();
                
                btn.disabled = false;
                text.textContent = '🤖 AI智能填充';
                alert('🎉 AI智能填充完成！\n✅ 已生成拼音、基本信息\n✅ 已创作记忆技巧和故事\n✅ 已生成练习题目');
            }, 3000);
        }

        // 生成示例数据
        function generateSampleData(character) {
            const samples = {
                '土': {
                    pinyin: 'tǔ',
                    strokes: 3,
                    radical: '土',
                    basicMeaning: '土地、泥土。指地面以下的泥沙混合物，也指本地的、本国的。在五行中代表中央。',
                    shapeFeatures: '字形像地面上的土堆，三画组成：上面一横代表地面，中间一竖代表从地面冒出的土堆，下面一横代表地基根基。',
                    memoryTips: '记忆口诀：一横地面一竖立，下面一横是根基。土字就像小土堆，三笔写出很整齐。',
                    evolution: '甲骨文：形似土堆，上宽下窄\n金文：保持土堆形状，笔画更加规整\n小篆：规范化为三横两竖的形态\n楷书：演变为现在的"土"字形',
                    originStory: '远古时代，我们的祖先过着农耕生活，土地是他们最珍贵的财富。他们观察到地面上经常有小土堆，就用三笔画出了土字的原型。',
                    extendedMeaning: '五行含义：土居五行之中，代表厚德载物、包容万物\n地理含义：本土、国土、领土\n品质含义：朴实、憨厚、踏实',
                    commonPhrases: '土地、土壤、泥土、国土、领土、本土、土豆、土木、水土、土方、沃土、净土、故土、热土',
                    exampleSentences: '小明在花园里挖土种花。\n农民伯伯在肥沃的土地上种庄稼。\n我们要保护祖国的每一寸土地。',
                    questions: '"土"字一共有几画？请按笔画顺序写出来。\n请写出五个带"土"字的词语，并选择一个造句。\n"土"字在古代象征着什么？\n土地对我们的生活有什么重要作用？\n看图识字：如果你看到一个小土堆，你能想到"土"字的哪个部分吗？'
                },
                '一': {
                    pinyin: 'yī',
                    strokes: 1,
                    radical: '一',
                    basicMeaning: '数词，最小的正整数。表示单一、第一、整个、全部的意思。',
                    shapeFeatures: '最简单的汉字，只有一横。象征着天地之间的一条线，代表着开始、起源、统一。',
                    memoryTips: '记忆要诀：一横就是一，简单明了记心里。手势记忆：伸出一根手指，就像"一"字的形状。',
                    evolution: '甲骨文就是一条横线，代表数字1\n金文保持横线形状\n小篆规范为标准横画\n楷书延续至今',
                    originStory: '传说盘古开天辟地时，天地混沌一片。盘古用斧子劈出了第一道光明，这就是"一"的起源。',
                    extendedMeaning: '哲学含义：道生一，一生二，二生三，三生万物\n数学含义：最小的自然数\n文化含义：专一、统一、第一',
                    commonPhrases: '一个、一天、一起、一样、第一、统一、专一、一心一意',
                    exampleSentences: '今天是一个美好的日子。\n我们一起去公园玩吧。\n这是我第一次看到彩虹。',
                    questions: '"一"字有几画？怎么写？\n从一到十，你能写出几个数字？\n"一心一意"是什么意思？\n生活中哪些东西是"一个"的？\n为什么"一"字这么简单却这么重要？'
                }
            };

            return samples[character] || {
                pinyin: `${character}的拼音`,
                strokes: 4,
                radical: character,
                basicMeaning: `"${character}"字的基本含义和用法说明...`,
                shapeFeatures: `"${character}"字的字形特征：结构分析、笔画特点、形状描述...`,
                memoryTips: `记忆"${character}"字的巧妙方法：口诀、联想、形象记忆...`,
                evolution: `"${character}"字的演变历程：甲骨文→金文→小篆→楷书的发展变化...`,
                originStory: `关于"${character}"字的起源故事：为什么会有这样的字形，背后有什么文化内涵...`,
                extendedMeaning: `"${character}"字的扩展含义：在不同语境和文化中的意义...`,
                commonPhrases: `${character}字、${character}语、${character}词、相关词组...`,
                exampleSentences: `包含"${character}"字的句子示例，适合儿童理解和学习...`,
                questions: `"${character}"字一共有几画？\n请写出三个带"${character}"字的词语\n"${character}"字是什么结构？\n"${character}"字在生活中有什么用处？\n你能用"${character}"字造一个句子吗？`
            };
        }

        // 导入数据
        function importData() {
            alert('📥 批量导入功能说明\n\n支持导入Excel/CSV/JSON格式的字根数据\n\n🎯 排序规则：\n• 初始导入380个字根：按笔画数从低到高排序\n• 后续新增字根：按导入时间排序\n\n📋 导入功能：\n• 自动验证数据格式\n• 重复数据检查\n• 批量数据处理\n• 导入进度显示\n• 自动生成课程编号\n\n💡 注意：课程数据直接来源于字根数据');
        }

        // 导出数据
        function exportData() {
            const dataStr = JSON.stringify(radicals, null, 2);
            const dataBlob = new Blob([dataStr], { type: 'application/json' });
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `字根数据_${new Date().toISOString().split('T')[0]}.json`;
            link.click();
            URL.revokeObjectURL(url);
            alert('数据导出成功！文件已下载到您的设备');
        }

        // 点击弹窗外部关闭
        document.getElementById('editor-modal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeEditor();
            }
        });

        // 切换字根隐藏状态
        function toggleRadical(id) {
            const radical = radicals.find(r => r.id === id);
            if (!radical) return;

            const action = radical.hidden ? '显示' : '隐藏';
            const confirmMessage = radical.hidden 
                ? `确定要将字根"${radical.character}"重新显示在课程中吗？` 
                : `确定要将字根"${radical.character}"从课程中隐藏吗？\n\n注意：隐藏后此字根不会出现在课程列表中，但数据仍会保留。`;

            if (confirm(confirmMessage)) {
                radical.hidden = !radical.hidden;
                
                updateStatistics();
                renderTable();
                renderPagination();
                
                alert(`✅ 字根"${radical.character}"已${action}！`);
            }
        }
    </script>
</body>
</html> 